package gold.digger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC47 {


    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        int[] visited = new int[nums.length];
        List<Integer> out = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        permuteUniqueDFS(nums, 0, visited, out, res);
        return res;
    }

    void permuteUniqueDFS(int[] nums, int level, int[] visited, List<Integer> out, List<List<Integer>> res) {
        if (level >= nums.length) {
            List<Integer> curPer = new ArrayList<>();
            for (int el : out) {
                curPer.add(el);
            }
            res.add(curPer);
            return;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (visited[i] == 1) continue;
            if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0) continue;
            visited[i] = 1;
            out.add(nums[i]);
            permuteUniqueDFS(nums, level + 1, visited, out, res);
            out.remove(out.size() - 1);
            visited[i] = 0;
        }
    }

    public static void main(String[] args) {
        LC47 an = new LC47();
        int[] arr = {1, 1, 2};

        System.out.println(an.permuteUnique(arr));
    }
}
